package com.zjdiepu.www.biz.third.net;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.JuheVehicleType;
import com.zjdiepu.www.base.lang.HttpClientException;
import com.zjdiepu.www.common.consts.SystemConsts;
import com.zjdiepu.www.common.consts.ThirdService;
import com.zjdiepu.www.common.util.UUIDFactory;
import com.zjdiepu.www.commpent.HttpClient;
import com.zjdiepu.www.config.JuheServiceProperty;
import com.zjdiepu.www.dao.third.JuheBrandMapper;
import com.zjdiepu.www.dao.third.JuheCarMapper;
import com.zjdiepu.www.dao.third.JuheCityMapper;
import com.zjdiepu.www.dao.third.JuheProvinceMapper;
import com.zjdiepu.www.dao.third.JuheSeriesMapper;
import com.zjdiepu.www.dao.third.JuheYearMapper;
import com.zjdiepu.www.ibiz.third.net.ISynCarService;
import com.zjdiepu.www.model.third.dto.JuheBrand;
import com.zjdiepu.www.model.third.dto.JuheCar;
import com.zjdiepu.www.model.third.dto.JuheCity;
import com.zjdiepu.www.model.third.dto.JuheProvince;
import com.zjdiepu.www.model.third.dto.JuheSeries;
import com.zjdiepu.www.model.third.dto.JuheYear;
import com.zjdiepu.www.model.third.ext.JuheBrandExt;
import com.zjdiepu.www.model.third.ext.JuheCarExt;
import com.zjdiepu.www.model.third.ext.JuheSeriesExt;
/**
 * 同步服务
 * @author xiongxiaotun
 * @date 2017年3月23日 下午4:10:44
 * @since v1.0.0
 * @update
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED, isolation = Isolation.READ_UNCOMMITTED, timeout = 60)
public class JuheSynCarServiceImpl extends BaseService implements ISynCarService {
	private static final Logger logger = LoggerFactory.getLogger(JuheSynCarServiceImpl.class);
	@Autowired
	private JuheProvinceMapper juheProvinceMapper;
	@Autowired
	private JuheCityMapper juheCityMapper;
	@Autowired
	private JuheBrandMapper juheBrandMapper;
	@Autowired
	private JuheSeriesMapper juheSeriesMapper;
	@Autowired
	private JuheCarMapper juheCarMapper;
	@Autowired
	private JuheYearMapper juheYearMapper;
	@Resource
	protected HttpClient httpClient;
	@Resource
	private JuheServiceProperty juheServiceProperty;
	/**
	 * 同步省份/城市
	 * @author xiongxiaotun@126.com
	 * @time 2017年3月23日 下午8:52:36
	 * @since 1.0.0
	 * @update
	 * @throws SocketTimeoutException
	 * @throws HttpClientException
	 */
	@Deprecated
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, timeout = 1000)
	public void synRegion() throws SocketTimeoutException, HttpClientException {
		Map<String, String> proParamMap = getJuheCommonParamMap(juheServiceProperty.getAppKey());
		String proJsonString = httpClient.get(ThirdService.JUHE_PROVINCE,
				proParamMap);
		List<JuheProvince> juheProvinces = commonProcessJsonResultFromJuhe(proJsonString, JuheProvince.class);
		if (CollectionUtils.isNotEmpty(juheProvinces)) {
			
			List<JuheCity> juheCities = new ArrayList<>();
			for(JuheProvince juheProvince : juheProvinces) {
				juheProvince.setId(UUIDFactory.getUUID());
				juheProvince.setDpStatus(DpStatus.NORMAL.getCode());
				
				String proId = juheProvince.getProId();
				Map<String, String> cityParamMap = getJuheCommonParamMap(juheServiceProperty.getAppKey());
				cityParamMap.put("province", proId);
				String cityJsonString = httpClient.get(ThirdService.JUHE_CITY,
						cityParamMap);
				List<JuheCity> currentJuheCities = commonProcessJsonResultFromJuhe(cityJsonString, JuheCity.class);
				if(CollectionUtils.isNotEmpty(currentJuheCities)) {
					
					for(JuheCity juheCity : currentJuheCities) {
						juheCity.setId(UUIDFactory.getUUID());
						juheCity.setDpStatus(DpStatus.NORMAL.getCode());
						juheCity.setProId(proId);
					}
					juheCities.addAll(currentJuheCities);
				}
			}
			
			if(CollectionUtils.isNotEmpty(juheCities)) {
				juheCityMapper.deleteAll();
				juheCityMapper.insertBatch(juheCities);
			}
			juheProvinceMapper.deleteAll();
			juheProvinceMapper.insertBatch(juheProvinces);
		}
	}
	/** 
	* @author zhangzj
	* @Title: synBrand 
	* @Description: 同步汽车品牌信息
	* @param @throws SocketTimeoutException
	* @param @throws HttpClientException    设定文件 
	* @return void    返回类型 
	* @version V1.0
	* @throws 
	*/
	@Override
	public List<String> saveSynBrand() {
		Map<String, String> brandParamMap = getJuheCommonParamMap(juheServiceProperty.getAppKey());
		List<String> listBrandJsonString=new ArrayList<String>();
		for(JuheVehicleType juheVehicleType : JuheVehicleType.values()) {
			brandParamMap.put("vehicle", juheVehicleType.getCode());
			String brandJsonString;
			try {
				brandJsonString = httpClient.get(ThirdService.JUHE_BRAND,brandParamMap);
				logger.debug(brandJsonString);
				listBrandJsonString.add(brandJsonString);
			} catch (SocketTimeoutException | HttpClientException e) {
				e.printStackTrace();
			}
		}
		return listBrandJsonString;
	}
	/** 
	* @author zhangzj
	* @Title: insertBrand 
	* @Description: 转换json字符串
	* @param @param brandJsonString    设定文件 
	* @return void    返回类型 
	* @version V1.0
	* @throws 
	*/
	private List<JuheBrand> handleBrandJsonString(String brandJsonString){
		List<JuheBrand> juheBrands = new ArrayList<>();
		JSONObject jsonObject = (JSONObject) JSONObject.parse(brandJsonString);
		String returnCode = jsonObject.getString("error_code");
		if(!SystemConsts.RETURN_SUCCESS_CODE.equals(returnCode)) {
			logger.error("invoke third service return error. errorCode is {}, errorMsg is {}.", returnCode, jsonObject.getString("reason"));
			throw new BaseException(returnCode, jsonObject.getString("reason"));
		}
		JSONObject resultJSONObject = jsonObject.getJSONObject("result");
		Set<String> pins  = resultJSONObject.keySet();
		if(CollectionUtils.isEmpty(pins)) {
			logger.error("拼音首字母为空或者转换错误!");
			throw new BaseException("errorMsg", "拼音首字母为空或者转换错误!");
		}
		for(String pin : pins) {
			JSONArray brandArray = resultJSONObject.getJSONArray(pin);
			List<JuheBrand> currentJuheBrands = brandArray.toJavaList(JuheBrand.class);
			if(CollectionUtils.isNotEmpty(currentJuheBrands)) {
				for(JuheBrand currentJuheBrand : currentJuheBrands){
					currentJuheBrand.setId(UUIDFactory.getUUID());
					currentJuheBrand.setDpStatus(DpStatus.NORMAL.getCode());
				}
				juheBrands.addAll(currentJuheBrands);
			}
		}
		return juheBrands;
	}
	/** 
	* @author zhangzj
	* @Title: insertBrand 
	* @Description: 把同步的汽车品牌信息保存到数据库
	* @param @param juheBrands    设定文件 
	* @return void    返回类型 
	* @version V1.0
	* @throws 
	*/
	private void insertBrand(List<JuheBrand> juheBrands){
		juheBrandMapper.insertBatch(juheBrands);
	}
	/**
	 * 同步汽车信息
	 * @author xiongxiaotun@126.com
	 * @time 2017年3月23日 下午8:52:36
	 * @since 1.0.0
	 * @update
	 * @throws SocketTimeoutException
	 * @throws HttpClientException
	 */
	@Deprecated
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, timeout = 1000)
	public void saveSynCar() {
		List<String> list = saveSynBrand();
		for (String brandString : list) {
			if(StringUtils.isEmpty(brandString)) continue;
			insertBrand(handleBrandJsonString(brandString));
		}
	}
	/**
	 * @throws HttpClientException 
	 * @throws SocketTimeoutException  
	* @author zhangzj
	* @Title: synSeries 
	* @Description: 同步车系列
	* @param @throws SocketTimeoutException
	* @param @throws HttpClientException    设定文件 
	* @return void    返回类型 
	* @version V1.0
	* @throws 
	*/
	@Deprecated
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, timeout = 1000)
	public void saveSeries() throws SocketTimeoutException, HttpClientException{
		JuheBrandExt juheBrandExt = new JuheBrandExt();
		juheBrandExt.withOutPage();
		juheBrandExt.notDeleted();
		List<JuheBrand> juheBrandsList=juheBrandMapper.selectByExt(juheBrandExt);
		if(CollectionUtils.isNotEmpty(juheBrandsList)) {
			List<JuheSeries> juheSeries = new ArrayList<>();
			synSeries(juheBrandsList, juheSeries);
			//同步车系
			juheSeriesMapper.insertBatch(juheSeries);
		}
	}
	/** 
	* @author zhangzj
	* @Title: synCars 
	* @Description: 同步车型
	* @param @throws SocketTimeoutException
	* @param @throws HttpClientException    设定文件 
	* @return void    返回类型 
	* @version V1.0
	* @throws 
	*/
	@Deprecated
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, timeout = 1000)
	public void saveSynCars() throws SocketTimeoutException, HttpClientException{
		JuheSeriesExt juheSeries= new JuheSeriesExt();
		juheSeries.withOutPage();
		juheSeries.notDeleted();
		//同步车型
		List<JuheSeries> juheSeriesList=juheSeriesMapper.selectByExt(juheSeries);
		System.out.println(juheSeriesList);
		if(CollectionUtils.isNotEmpty(juheSeriesList)) {
			
			List<JuheCar> juheCars = new ArrayList<>();
			synCar(juheSeriesList, juheCars);
			juheCarMapper.insertBatch(juheCars);
			
		}
	}
	/** 
	* @author zhangzj
	* @Title: synYear 
	* @Description: 同步年份
	* @param @throws SocketTimeoutException
	* @param @throws HttpClientException    设定文件 
	* @return void    返回类型 
	* @version V1.0
	* @throws 
	*/
	@Deprecated
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, timeout = 1000)
	public void synYear() throws SocketTimeoutException, HttpClientException{
		JuheCarExt juheCar=new JuheCarExt();
		juheCar.withOutPage();
		juheCar.notDeleted();
		List<JuheCar> juheCarsList=juheCarMapper.selectByExt(juheCar);
		if(CollectionUtils.isNotEmpty(juheCarsList)) {
			List<JuheYear> juheYears = new ArrayList<>();
			synYear(juheCarsList, juheYears);
			if(CollectionUtils.isNotEmpty(juheYears)) {
				juheYearMapper.insertBatch(juheYears);
			}
		}
	}
	
	/**
	 * 同步车系
	 * @author xiongxiaotun@126.com
	 * @time 2017年3月23日 下午11:05:47
	 * @since 1.0.0
	 * @update
	 * @param juheBrands
	 * @param juheSeries
	 */
	private void synSeries(List<JuheBrand> juheBrands, List<JuheSeries> juheSeries) throws SocketTimeoutException, HttpClientException {
		if(CollectionUtils.isEmpty(juheBrands)) {
			logger.error("汽车品牌为空!");
			throw new BaseException("errorMsg","汽车品牌为空!");
		}
		for(JuheBrand juheBrand : juheBrands) {
			Map<String, String> seriesParamMap = getJuheCommonParamMap(juheServiceProperty.getAppKey());
			seriesParamMap.put("brand", juheBrand.getThirdId());
			String seriesJsonString = httpClient.get(ThirdService.JUHE_SERIES,
					seriesParamMap);
			logger.debug("同步车系成功："+seriesJsonString);
			if(!StringUtils.isEmpty(seriesJsonString)) {
				JSONObject jsonObject = (JSONObject) JSONObject.parse(seriesJsonString);
				checkJuheResponse(jsonObject, logger);
				JSONObject resultJSONObject = jsonObject.getJSONObject("result");
				Set<String> pinpais = resultJSONObject.keySet();
				if(CollectionUtils.isNotEmpty(pinpais)) {
					
					for(String pinpai : pinpais) {
						
						JSONArray pinpaiArray = resultJSONObject.getJSONArray(pinpai);
						if(null == pinpaiArray || pinpaiArray.isEmpty()) {
							
							continue;
						}
						for(int i = 0; i < pinpaiArray.size(); i++) {
							
							JSONObject juheSeriesJSONOjbect = pinpaiArray.getJSONObject(i);
							String brandId = juheBrand.getThirdId();
							String ppid = juheSeriesJSONOjbect.getString("ppid");
							String ppname = juheSeriesJSONOjbect.getString("ppname");
							
							JSONArray currentJuheSeriesJSONArray = juheSeriesJSONOjbect.getJSONArray("xilie");
							if(null == currentJuheSeriesJSONArray || currentJuheSeriesJSONArray.isEmpty()) {
								
								continue;
							}
							List<JuheSeries> currentJuheSeries = currentJuheSeriesJSONArray.toJavaList(JuheSeries.class);
							if(CollectionUtils.isNotEmpty(currentJuheSeries)) {
								for(JuheSeries juheSery : juheSeries) {
									juheSery.setId(UUIDFactory.getUUID());
									juheSery.setDpStatus(DpStatus.NORMAL.getCode());
									
									juheSery.setBrandId(brandId);
									juheSery.setPpid(ppid);
									juheSery.setPpname(ppname);
								}
								juheSeries.addAll(currentJuheSeries);
							}
						}
					}
				}
			}
		}
	}
	
	/**
	 * 同步车型
	 * @author xiongxiaotun@126.com
	 * @time 2017年3月23日 下午11:05:47
	 * @since 1.0.0
	 * @update
	 * @param juheSeries
	 * @param juheCars
	 */
	private void synCar(List<JuheSeries> juheSeries, List<JuheCar> juheCars) throws SocketTimeoutException, HttpClientException {
		if(CollectionUtils.isNotEmpty(juheSeries)) {
			
			for(JuheSeries juheSery : juheSeries) {
				Map<String, String> carParamMap = getJuheCommonParamMap(juheServiceProperty.getAppKey());
				carParamMap.put("series", juheSery.getXlid());
				String carJsonString = httpClient.get(ThirdService.JUHE_CAR,
						carParamMap);
				logger.debug("同步车型成功：", carJsonString);
				if(!StringUtils.isEmpty(carJsonString)) {
					JSONObject jsonObject = (JSONObject) JSONObject.parse(carJsonString);
					checkJuheResponse(jsonObject, logger);
					
					JSONArray resultJSONArray = jsonObject.getJSONObject("result").getJSONArray("data");
							
					if(null == resultJSONArray || resultJSONArray.isEmpty()) {
						continue;
					}
					for(int i = 0; i < resultJSONArray.size(); i++) {
						
						JSONObject juheCarJSONOjbect = resultJSONArray.getJSONObject(i);
						String seriesId = juheSery.getXlid();
						Integer fbPyear = juheCarJSONOjbect.getInteger("pyear");
						
						JSONArray currentJuheCarJSONArray = juheCarJSONOjbect.getJSONArray("chexing_list");
						if(null == currentJuheCarJSONArray || currentJuheCarJSONArray.isEmpty()) {
							
							continue;
						}
						List<JuheCar> currentJuheCars = currentJuheCarJSONArray.toJavaList(JuheCar.class);
						if(CollectionUtils.isNotEmpty(currentJuheCars)) {
							for(JuheCar juheCar : currentJuheCars) {
								juheCar.setId(UUIDFactory.getUUID());
								juheCar.setDpStatus(DpStatus.NORMAL.getCode());
								juheCar.setSeriesId(seriesId);
								juheCar.setFbPyear(fbPyear.toString());
							}
							juheCars.addAll(currentJuheCars);
						}
					}
				}
				
			}
		}
	}
	
	/**
	 * 同步车型年份
	 * @author xiongxiaotun@126.com
	 * @time 2017年3月23日 下午11:05:47
	 * @since 1.0.0
	 * @update
	 * @param juheCars
	 * @param juheYears
	 */
	private void synYear(List<JuheCar> juheCars, List<JuheYear> juheYears) throws SocketTimeoutException, HttpClientException {
		if(CollectionUtils.isNotEmpty(juheCars)) {
			
			for(JuheCar juheCar : juheCars) {
				Map<String, String> yearParamMap = getJuheCommonParamMap(juheServiceProperty.getAppKey());
				yearParamMap.put("car", juheCar.getCarId());
				
				String yearJsonString = httpClient.get(ThirdService.JUHE_YEAR,
						yearParamMap);
				
				if(!StringUtils.isEmpty(yearJsonString)) {
					JSONObject jsonObject = (JSONObject) JSONObject.parse(yearJsonString);
					checkJuheResponse(jsonObject, logger);
					JSONArray resultJSONArray = jsonObject.getJSONArray("result");
							
					if(null == resultJSONArray || resultJSONArray.isEmpty()) {
						
						continue;
					}
					for(int i = 0; i < resultJSONArray.size(); i++) {
						String carId = juheCar.getCarId();
						String year = resultJSONArray.getString(i);
						JuheYear juheYear = new JuheYear();
						juheYear.setId(UUIDFactory.getUUID());
						juheYear.setDpStatus(DpStatus.NORMAL.getCode());
						
						juheYear.setCarId(carId);
						juheYear.setPyear(year);
						juheYears.add(juheYear);
					}
				}
			}
		}
	}
	
	/**
	 * @throws HttpClientException 
	 * @throws SocketTimeoutException  
	* @author zhangzj
	* @Title: incrementSeries 
	* @Description: 同步增量的汽车品牌和系列信息
	* @param     设定文件 
	* @return void    返回类型 
	* @version V1.0
	* @throws 
	*/
	@Deprecated
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED, timeout = 1000)
	public void incrementSeries() throws SocketTimeoutException, HttpClientException{
		//从数据库取系列
		JuheSeriesExt juheSeriesExt= new JuheSeriesExt();
		juheSeriesExt.withOutPage();
		juheSeriesExt.notDeleted();
		List<JuheSeries> juheSeriesListDb=juheSeriesMapper.selectByExt(juheSeriesExt);
		List<String> listSeriesIdDb= new ArrayList<String>();
		for (JuheSeries juheSeriess : juheSeriesListDb) {
			listSeriesIdDb.add(juheSeriess.getXlid());
		}
		//从聚合取系列
		List<String> list=saveSynBrand();
		List<JuheBrand> juheBrandsList=new ArrayList<JuheBrand>();
		for (String brandString : list) {
			if(StringUtils.isEmpty(brandString)) continue;
			juheBrandsList.addAll(handleBrandJsonString(brandString));
		}
		List<JuheSeries> juheSeries = new ArrayList<>();
		List<String> listXlIdJuhe=new ArrayList<String>();
		synSeries(juheBrandsList, juheSeries);
		for (JuheSeries juheSeries2 : juheSeries) {
			listXlIdJuhe.add(juheSeries2.getXlid());
		}
		//比较juhe.cn上有但数据库没有更新的汽车系列
		List<String> newSeriesIdList= new ArrayList<String>();
		for(String seriesId:listXlIdJuhe){
			if(!listSeriesIdDb.contains(seriesId)){  
				newSeriesIdList.add(seriesId);
            }  
		}
		for (String seriesId : newSeriesIdList) {
			for (JuheSeries juhePo : juheSeries) {
				if(juhePo.getXlid().equals(seriesId)){
					juheSeriesMapper.insert(juhePo);
				}
				
			}
		}
	}
}
